package com.css.apps.base.menu.service;

import com.css.apps.base.menu.model.SMenu;
import com.css.common.plugins.impl.AbstractConfigurablePlugin;
import com.css.core.model.IUser;
import com.css.core.model.tree.Tree;
import com.css.core.model.tree.TreeCache;
import com.css.core.model.tree.TreeNode;
import com.css.db.config.ConfigurationManager;
import com.css.db.query.QueryCache;
import com.css.util.StringHelper;
import com.css.webbase.WebBaseUtil;
import com.css.webbase.menu.IMenuProvider;
import com.css.webbase.menu.MenuItem;

import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;


public class DBMenuProvider extends AbstractConfigurablePlugin implements IMenuProvider {
	private boolean cached = true;
	private String cacheName = "_user_menu_cache/";
	private boolean ignoreOneTop = false;
	private String sysId = null;

	@Override
	protected void doConfig(Map<String, String> configMap) {
		if (configMap == null)
			return;
		if ("false".equals(configMap.get("cache"))) {
			cached = false;
		}
		if ("true".equals(configMap.get("ignoreOneTop"))) {
			ignoreOneTop = true;
		}
	}

	@Override
	public List<MenuItem> getAllMenu(IUser user) {
		java.util.List<MenuItem> items = null;
		if (cached) {
			items = getCachedListItem(user);
			if (items != null)
				return items;
		}
		Tree tree = new TreeCache(SMenu.class);
		// 根节点
		List<TreeNode> roots = tree.getRoot();
		if (roots != null && roots.size() != 0) {
			items = new java.util.ArrayList<MenuItem>();
			for (TreeNode root : roots) {
				int level = 1;
				MenuItem mi = transpass(root, level, user);
				if (mi != null)
					items.add(mi);
			}
			if (items.size() == 1 && ignoreOneTop) {
				MenuItem mi = items.get(0);
				if (StringHelper.isEmptyByTrim(mi.getPath()))
					items = mi.getMenus();
			}
			if (cached)
				cacheListItem(user, items);
		}
		return items;
	}

	/**
	 * 遍历菜单树，获取系统菜单
	 * @param node
	 * @param level
	 * @param user
	 * @return
	 */
	private MenuItem transpass(TreeNode node, int level, IUser user) {
		// 获取所有子节点
		List<TreeNode> sMenuNodes = node.getChildren();
		String curMenuId = node.getNodeId();
		MenuItem menuItem = new MenuItem();
		SMenu menu = QueryCache.get(SMenu.class, curMenuId);
		if (menu != null && "1".equals(menu.getOpenFlag())) {
			/* 下面这句代码控制菜单按照系统归类，注释掉可以在base中看到别的系统中定义的菜单 2021 0709
			if (!getSysId().equals(menu.getSysId())) {
				return null;
			}*/
			String funcId = menu.getFuncId();
			String url = menu.getUrl();
			/*
			 * Set<String> funcCodes = user.getFunctions(); if(isSecured &&
			 * !(StringHelper.isEmptyByTrim(funcId) &&
			 * StringHelper.isEmptyByTrim(url)) && !funcCodes.contains(funcId))
			 * return null;
			 */
			// 暂时修改，for测试
			if (!(StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url))
					&& !WebBaseUtil.hasPrivilege(user, funcId))
				return null;
			menuItem.setId(menu.getMenuId());
			menuItem.setIcon(menu.getIcon());
			menuItem.setLevel(level);
			menuItem.setName(menu.getMenuName());
			menuItem.setOpenIcon(menu.getIcon());
			menuItem.setPath(url);
			menuItem.setFuncode(menu.getFuncId());
			menuItem.setParentId(menu.getParentId());
			menuItem.setVisible(true);
			if (sMenuNodes.isEmpty())
				menuItem.setIsLast(true);
			else
				menuItem.setIsLast(false);

		} else
			return null;

		if (sMenuNodes != null && !sMenuNodes.isEmpty()) {
			for (TreeNode node1 : sMenuNodes) {
				MenuItem mi = transpass(node1, level + 1, user);
				if (mi != null)
					menuItem.getMenus().add(mi);
			}
			String funcId = menu.getFuncId();
			String url = menu.getUrl();

			if (StringHelper.isEmptyByTrim(funcId) && StringHelper.isEmptyByTrim(url) && menuItem.getMenus().isEmpty())
				return null;
		}
		return menuItem;
	}

	/**
	 * 从缓存中获取用户菜单
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<MenuItem> getCachedListItem(IUser user) {
		if (user == null)
			return null;
		return (List<MenuItem>) com.css.db.memcached.MemCachedFactory.get(getUserKey(user));
	}

	/**
	 * 缓存用户菜单
	 * 
	 * @return
	 */
	private void cacheListItem(IUser user, List<MenuItem> items) {
		if (items == null)
			return;
		if (user == null)
			return;
		com.css.db.memcached.MemCachedFactory.set(getUserKey(user), items, ConfigurationManager.getCacheTime());
	}

	/**
	 * 返回用户缓存键值
	 * 
	 * @param user
	 * @return
	 */
	private String getUserKey(IUser user) {
		return cacheName + "/" + user.getOrganId() + "/" + user.getUserId();
	}

	private String getSysId() {
		if (sysId == null) {
			Properties prop = new Properties();
			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			try {
				FileInputStream fis = new FileInputStream(path + "appconfig.properties");
				prop.load(fis);
				sysId = prop.getProperty("app.system.id");
			} catch (Exception ex) {
				System.out.println(ex);
			}
		}
		// sysId =
		// SystemConfig.getSystemConfig().getSysConfigure("app.system.id");
		return sysId;
	}
}
